import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:provider/provider.dart' as provider;
import 'package:scoped_model/scoped_model.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'stores/chat_store.dart';
import 'routes/app_router.dart';
import 'models/counter_model.dart';
import 'models/task_model.dart';
import 'models/expense_model.dart';
import 'services/task_service.dart';
import 'services/expense_service.dart';
import 'screens/scoped_model_demo_screen.dart';
import 'screens/riverpod_demo_screen.dart';
import 'screens/riverpod_hive_demo_screen.dart';
import 'screens/expense_home_screen.dart';

void main() async {
  // 在运行应用前初始化日期格式化和Hive
  WidgetsFlutterBinding.ensureInitialized();
  await initializeDateFormatting('zh_CN', null);

  // 初始化Hive
  await Hive.initFlutter();

  // 注册Hive适配器
  Hive.registerAdapter(TaskModelAdapter());
  Hive.registerAdapter(ExpenseModelAdapter());
  Hive.registerAdapter(ExpenseTypeAdapter());
  Hive.registerAdapter(ExpenseCategoryAdapter());

  // 初始化服务
  await TaskService.init();
  await ExpenseService.init();

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    // 创建ChatStore实例
    final chatStore = ChatStore()..initData();

    // 创建路由配置
    final appRouter = AppRouter(chatStore: chatStore);

    // 创建CounterModel实例用于Scoped Model demo
    final counterModel = CounterModel();

    return ScreenUtilInit(
      designSize: const Size(375, 812),
      minTextAdapt: true,
      splitScreenMode: true,
      child: ProviderScope(
        child: provider.MultiProvider(
          providers: [
            provider.Provider<ChatStore>(create: (_) => chatStore),
            // 添加Scoped Model支持
            provider.Provider<CounterModel>(create: (_) => counterModel),
          ],
          child: ScopedModel<CounterModel>(
            model: counterModel,
            child: MaterialApp(
              title: 'Flutter Demo - MobX, Scoped Model & Riverpod',
              theme: ThemeData(
                colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
                useMaterial3: true,
                // 自定义AppBar主题
                appBarTheme: const AppBarTheme(centerTitle: true, elevation: 0),
              ),
              debugShowCheckedModeBanner: false,
              // 使用简单的路由来展示不同的状态管理demo
              home: const DemoSelectionScreen(),
              routes: {
                '/scoped-model-demo': (context) => const ScopedModelDemoScreen(),
                '/riverpod-demo': (context) => const RiverpodDemoScreen(),
                '/riverpod-hive-demo': (context) =>
                    const RiverpodHiveDemoScreen(),
                '/expense-demo': (context) => const ExpenseHomeScreen(),
                '/mobx-demo': (context) =>
                    MaterialApp.router(routerConfig: appRouter.router).home!,
              },
            ),
          ),
        ),
      ),
    );
  }
}

/// Demo选择屏幕
/// 让用户选择查看哪个状态管理demo
class DemoSelectionScreen extends StatelessWidget {
  const DemoSelectionScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('状态管理演示'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              '选择状态管理演示',
              style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24),

            // Scoped Model Demo卡片
            Card(
              child: InkWell(
                onTap: () {
                  Navigator.pushNamed(context, '/scoped-model-demo');
                },
                child: const Padding(
                  padding: EdgeInsets.all(20.0),
                  child: Column(
                    children: [
                      Icon(Icons.account_tree, size: 48, color: Colors.blue),
                      SizedBox(height: 12),
                      Text(
                        'Scoped Model Demo',
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 8),
                      Text(
                        '学习如何使用Scoped Model进行状态管理。\n包含带用户管理的计数器应用。',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.grey, fontSize: 13),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ),
            ),

            const SizedBox(height: 16),

            // Riverpod Demo卡片
            Card(
              child: InkWell(
                onTap: () {
                  Navigator.pushNamed(context, '/riverpod-demo');
                },
                child: const Padding(
                  padding: EdgeInsets.all(20.0),
                  child: Column(
                    children: [
                      Icon(Icons.water_drop, size: 48, color: Colors.purple),
                      SizedBox(height: 12),
                      Text(
                        'Riverpod Demo',
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 8),
                      Text(
                        '使用Riverpod的现代状态管理。\n包含providers、计算值和设置。',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.grey, fontSize: 13),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ),
            ),

            const SizedBox(height: 16),

            // Riverpod + Hive Demo卡片
            Card(
              child: InkWell(
                onTap: () {
                  Navigator.pushNamed(context, '/riverpod-hive-demo');
                },
                child: const Padding(
                  padding: EdgeInsets.all(20.0),
                  child: Column(
                    children: [
                      Icon(
                        Icons.integration_instructions,
                        size: 48,
                        color: Colors.indigo,
                      ),
                      SizedBox(height: 12),
                      Text(
                        'Riverpod + Hive Demo',
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 8),
                      Text(
                        '集成Riverpod状态管理和Hive本地数据库的任务管理应用。\n具有响应式UI的完整CRUD操作。',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.grey, fontSize: 13),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 记账应用Demo卡片
            Card(
              child: InkWell(
                onTap: () {
                  Navigator.pushNamed(context, '/expense-demo');
                },
                child: const Padding(
                  padding: EdgeInsets.all(20.0),
                  child: Column(
                    children: [
                      Icon(
                        Icons.account_balance_wallet,
                        size: 48,
                        color: Color(0xFF6BB6FF),
                      ),
                      SizedBox(height: 12),
                      Text(
                        '记账应用 Demo',
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 8),
                      Text(
                        '使用Riverpod状态管理的粉嫩蓝色系记账应用。\n支持收支记录、分类管理、统计图表等功能。',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.grey, fontSize: 13),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ),
            ),

            const SizedBox(height: 16),

            // MobX Demo卡片
            Card(
              child: InkWell(
                onTap: () {
                  // 导航到现有的MobX聊天demo
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => provider.Provider<ChatStore>(
                        create: (_) => ChatStore()..initData(),
                        child: MaterialApp.router(
                          routerConfig: AppRouter(
                            chatStore: ChatStore()..initData(),
                          ).router,
                        ),
                      ),
                    ),
                  );
                },
                child: const Padding(
                  padding: EdgeInsets.all(20.0),
                  child: Column(
                    children: [
                      Icon(Icons.chat, size: 48, color: Colors.green),
                      SizedBox(height: 12),
                      Text(
                        'MobX Chat Demo',
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 8),
                      Text(
                        '现有的基于MobX的聊天应用演示。\n包含聊天列表和详情屏幕。',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.grey, fontSize: 13),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ),
            ),

            const SizedBox(height: 24),

            // 说明文本
            Container(
              padding: const EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(8.0),
              ),
              child: const Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '关于状态管理：',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 8),
                  Text('• Scoped Model：简单轻量的状态管理解决方案'),
                  Text('• Riverpod：现代的、编译安全的provider状态管理'),
                  Text('• 记账应用：使用Riverpod的完整记账应用示例'),
                  Text('• MobX：具有自动UI更新的响应式状态管理'),
                  Text('• 所有演示展示了管理应用状态的不同方法'),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
